import axios from 'axios'
import store from '@/store'
import router from '@/router'
import { Message } from 'element-ui'
import { getTokenTime } from '@/utils/auth.js'

const TimeOut = 2 * 60 * 60 * 1000
// const TimeOut = 3 * 1000

// create an axios instance
const request = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})
// 请求拦截器
request.interceptors.request.use((config) => {
  if (store.state.user.token) {
    if (isTimeOut()) {
      store.commit('user/removeToken', null)
      router.push('/login')
      return Promise.reject(new Error('token已过期'))
    }
    config.headers.Authorization = store.state.user.token
  }
  return config
})
// 响应拦截器
request.interceptors.response.use((res) => {
  const { meta } = res.data
  if (meta && meta.status === 200 || meta.status === 201) {
    return res.data
  } else {
    Message.error(meta.msg)
    return Promise.reject(new Error(meta.msg))
  }
}, (err) => {
  if (err.response && err.response.status === 401) {
    Message.error('登录已失效')
    store.commit('user/removeToken')
    router.push('login')
  } else {
    Message.error(err.message)
  }
  return Promise.reject(new Error(err))
})

// 封装时间戳函数
function isTimeOut() {
  const localTime = getTokenTime()
  const currentTime = Date.now()
  const time = currentTime - localTime
  return time >= TimeOut
}
export default request
